package com.example.moudlelibrary.controller;

import com.example.moudlelibrary.tools.DockerService;
import com.example.moudlelibrary.tools.FileOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by HeYuanqing on 2023/09/04  20:44
 **/
@CrossOrigin
@RestController
public class FDSController {
    //    模型存储地址
    String modelPath = "E:\\models\\FDS";

    @PostMapping(value = "/uploadInput")
    public ResponseEntity<String> uploadInput(@RequestParam("file") MultipartFile file) {
        try {
            // 获取上传的文件名
            String fileName = file.getOriginalFilename();

            // 指定文件保存的本地路径
            String filePath = modelPath + "\\FDSDemo.fds";

            // 将文件保存到本地
            File localFile = new File(filePath);
            file.transferTo(localFile);

            return ResponseEntity.ok("文件上传成功：" + fileName);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("文件上传失败：" + e.getMessage());
        }
    }

    @GetMapping(value = "/run")
    public boolean run() {
        String modelName = "fds5.exe";
        String params = "FDSDemo.fds";
        if (!FileOperator.IsFielExists(modelPath + "\\" + params)) {
            System.out.println("输入文件不存在！");
            return false;
        }
        String command = "cmd /C cd /d " + modelPath + "&& " + modelName + " " + params;
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        try {
            p.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
//        输出文件打包

        String[] fileNames = "room_fire.end,room_fire.out,room_fire.smv,room_fire_0001_00000002_00.q,room_fire_0001_00000004_00.q,room_fire_0001_00000006_00.q,room_fire_0001_00000008_00.q,room_fire_0001_00000010_00.q,room_fire_01.s3d,room_fire_01.s3d.sz,room_fire_02.s3d,room_fire_02.s3d.sz,room_fire_hrr.csv".split(",");
        // 要创建的ZIP文件的路径和名称
        String zipFilePath = modelPath + "\\FDSResultFile.zip";

        // 要添加到ZIP文件的文件列表
        for (int i = 0; i < fileNames.length; i++) {
            fileNames[i] = modelPath + "\\" + fileNames[i];
        }
        FileOperator.FileToZip(fileNames, zipFilePath);
//        删除打包好的文件
        FileOperator.DeleteFiles(fileNames);
        System.out.println("模型调用完毕！");
        return true;
    }

    @GetMapping(value = "getResult")
    public ResponseEntity<Resource> getResult() throws IOException {
        String zipFilePath = modelPath + "\\FDSResultFile.zip";
        if (FileOperator.IsFielExists(zipFilePath)) {
            // 构建文件路径
            Path filePathu = Paths.get(zipFilePath);
            Resource resource = new UrlResource(filePathu.toUri());
            // 确保文件存在并可读
            if (resource.exists() && resource.isReadable()) {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment", "FDSResultFile.zip");

                // 返回文件响应
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(resource);
            } else {
                // 文件不存在或不可读，返回404错误
                return ResponseEntity.notFound().build();
            }
        }
        return ResponseEntity.notFound().build();
    }


}
